package com.ama.controller;

import com.ama.dao.ApplyDao;
import com.ama.dao.ContractDao;
import com.ama.dao.CostDao;
import com.ama.dao.StaffDao;
import com.ama.pojo.*;
import com.ama.service.*;
import com.ama.utils.DateUtil;
import com.ama.utils.GetNumber;
import com.ama.utils.NumberUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
public class ApplyDorController {

    @Autowired
    EstateService estateService;
    @Autowired
    BuildService buildService;
    @Autowired
    RoomService roomService;
    @Autowired
    BedService bedService;
    @Autowired
    StaffService staffService;

    @Autowired
    ApplyDao applyDao;
    @Autowired
    ContractDao contractDao;
    @Autowired
    StaffDao staffDao;
    @Autowired
    CostDao costDao;


    @RequestMapping("/applyDormitory")
    public String applyDormitory(HttpServletRequest request, HttpSession session) {
        System.out.println("-------宿舍申请-------");

        Long propertyId = Long.valueOf(request.getParameter("propertyId"));
        Long staffId = Long.valueOf(request.getParameter("staffId"));
        Long estateId = Long.valueOf(request.getParameter("estateId"));
        Long buildId = Long.valueOf(request.getParameter("buildId"));
        Long roomId = Long.valueOf(request.getParameter("roomId"));
        Long bedId = Long.valueOf(request.getParameter("bedId"));

        /**
         * 产生宿舍申请单
         */
        String applyNum = request.getParameter("applyNum");
        String applyReason = request.getParameter("applyReason");
        System.out.println(applyNum);
        Date date = new Date();
        Apply apply = new Apply();
        apply.setApplyNum(applyNum);
        apply.setApplyDate(date);
        apply.setStaffId(staffId);
        apply.setPropertyId(propertyId);
        apply.setEstateId(estateId);
        apply.setBuildId(buildId);
        apply.setRoomId(roomId);
        apply.setBedId(bedId);
        apply.setApplyReason(applyReason);
        apply.setApplyState(0);
        applyDao.insertApply(apply);

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("apply_num", applyNum);
        Long applyId = applyDao.selectOne(wrapper).getApplyId();

        /**
         * 产生费用账单
         */
        Room croom = roomService.selectById(roomId);
        Cost cost = new Cost();
        cost.setCostNum(GetNumber.getDocumentNumber("COS","cost"));
        cost.setStaffId(staffId);
        cost.setPropertyId(propertyId);
        cost.setRoomId(roomId);
        cost.setBedId(bedId);
        cost.setCostTax(0.5);
        double roomcost = croom.getRoomRentarea()*croom.getRoomPrice() + croom.getRoomPublicarea()*1;
        double taxAmount = (croom.getRoomRentarea()*croom.getRoomPrice() + croom.getRoomPublicarea()*1)*0.5;
        cost.setCostTaxamount(NumberUtils.round( taxAmount,2));
        cost.setCostWater(20.3);
        cost.setCostElec(84.8);
        cost.setCostAmount(taxAmount+roomcost+cost.getCostElec()+cost.getCostWater());
        cost.setCostCreatdate(date);
        cost.setCostEnddate(DateUtil.strToDate(DateUtil.getFromNow(90)));
        cost.setCostShouldpay(0.0);
        cost.setCostRecentpay(0.0);
        cost.setCostLastpay(0.0);
        cost.setCostState(0);//1已缴费，0等待确认，-1未缴费，-2超时尽快缴费
        costDao.insertCost(cost);

        QueryWrapper cwrapper = new QueryWrapper();
        cwrapper.eq("cost_num", cost.getCostNum());
        Long costId = costDao.selectOne(cwrapper).getCostId();


        /**
         * 产生合同单
         */

        String contractNum = GetNumber.getDocumentNumber("CON","contract");
        Contract contract = new Contract();
        contract.setContractNum(contractNum);
        contract.setStaffId(staffId);
        contract.setPropertyId(propertyId);
        contract.setContractArea(croom.getRoomRentarea());
        contract.setContractTax(0.05);
        contract.setBigindate(date);
        contract.setEnddate(DateUtil.strToDate(DateUtil.getFromNow(90)));
        contract.setContractState(0);
        contractDao.insert(contract);

        QueryWrapper conwrapper = new QueryWrapper();
        conwrapper.eq("contract_num", contract.getContractNum());
        Long contractId = contractDao.selectOne(conwrapper).getContractId() ;

        /**
         * 床铺设为0待定
         */
        Bed bed = new Bed();
        bed.setBedId(bedId);
        bed.setBedState(0);
        bedService.updateByIdSelective(bed);

        /**
         * 检查房间是否还有空床位
         */
        List<Bed> beds = bedService.selectByRoomId(roomId);
        int i;
        for (i = 0; i < beds.size(); i++) {
            if (beds.get(i).getBedState() == 1) {
                break;
            }
        }
        if (i == beds.size()) {
            Room room = new Room();
            room.setRoomId(roomId);
            room.setRoomState(-1);
            roomService.updateByIdSelective(room);
        }

        /**
         * 检查楼栋是否还有空房间
         */

        List<Room> rooms = roomService.selectByBuildId(buildId);
        int j;
        for (j = 0; j < rooms.size(); j++) {
            if (rooms.get(i).getRoomState() == 1) {
                break;
            }
        }
        if (i == rooms.size()) {
            Build build = new Build();
            build.setBuildId(buildId);
            build.setBuildState(-1);
            buildService.updateByIdSelective(build);
        }


        /**
         * 更改员工信息,session更新
         */
        Staff staff = (Staff) session.getAttribute("user");
        staff.setEstateId(estateId);
        staff.setBuildId(buildId);
        staff.setRoomId(roomId);
        staff.setBedId(bedId);
        staff.setApplyId(applyId);
        staff.setCostId(costId);
        staff.setContractId(contractId);

        staffService.updateByIdSelective(staff);
        Staff newStaff = staffService.selectById(staffId);
        session.setAttribute("user", newStaff);
        System.out.println(newStaff);

        return "success/apply_success";
    }

    /**
     * 撤销申请状态
     */
    @RequestMapping("/cancelApply")
    public String cancelApply(HttpSession session) {
        Staff staff = (Staff) session.getAttribute("user");
        Long bedId = staff.getBedId();
        Long roomId = staff.getRoomId();
        Long buildId = staff.getBuildId();
        Long estateId = staff.getEstateId();
        /**
         * 床铺设为1释放
         */
        Bed bed = new Bed();
        bed.setBedId(bedId);
        bed.setBedState(1);
        bedService.updateByIdSelective(bed);

        /**
         * 检查房间床位释放1
         */

        Room room = new Room();
        room.setRoomId(roomId);
        room.setRoomState(1);
        roomService.updateByIdSelective(room);


        /**
         * 检查楼栋释放1
         */
        Build build = buildService.selectById(buildId);
        build.setBuildId(buildId);
        build.setBuildState(1);
        buildService.updateByIdSelective(build);

        //更新apply表的状态
        Long applyId = staff.getApplyId();
        Apply apply = new Apply();
        apply.setApplyId(applyId);
        apply.setApplyState(-1);
        applyDao.updateByPrimaryKeySelective(apply);

        //更新cost表的状态
        Long costId = staff.getCostId();
        Cost cost = new Cost();
        cost.setCostId(costId);
        cost.setCostState(-3);
        costDao.updateByPrimaryKeySelective(cost);

        //如果有合同表 更改终止人
        Long contractId = staff.getContractId();
        if (contractId != null) {
            Contract contract = new Contract();
            contract.setContractId(contractId);
            Date date = new Date();
            contract.setTerminalDate(date);
            contract.setContractState(-1);
            contract.setTerminalPerson(staff.getStaffName());
            contract.setTerminalReason("员工主动撤销！");
            contractDao.updateByPrimaryKeySelective(contract);
        }


        staff.setBedId(null);
        staff.setRoomId(null);
        staff.setBuildId(null);
        staff.setEstateId(null);
        staff.setApplyId(null);
        staff.setCostId(null);
        staff.setContractId(null);
        //更新员工信息
        //更新员工信息
        UpdateWrapper<Staff> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("staff_id",staff.getStaffId());
        staffDao.update(staff,updateWrapper);
        return "redirect:/success/cancelApply_success.jsp";
    }
}
